<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/15 0015
 * Time: 上午 11:44
 */
namespace app\api\controller;

use app\admin\model\Usersettlement;
use app\common\model\Distribution;
use app\common\model\Userstore;
use app\common\validate\bandUserInfoValidate;
use think\Db;
use think\Exception;
use think\Request;

class Member extends Base{



    public function getMember(Request $request){
        $param = $request->param();
        if(!$param['memberId']){
            return show(config('status.ERROR_STATUS'),'缺少参数用户ID','缺少参数用户ID');
        }
        $Member = \app\common\model\Member::where(['id'=>$param['memberId'],'status'=>1])->find();
        if($Member){
            //贡献佣金
            $memAllDis = $this->getmemAllDis($Member->id);
            $Member['memAllDis'] = $memAllDis;
            return show(config('status.SUCCESS_STATUS'),'ok',$Member);
        }else{
            return show(2,'',null);
        }
    }

    /**
     * 绑定上下级关系
     * @return \think\response\Json
     */
    public function bindRelationship(Request $request){
        $param = $request->param();
        //1.判断分享的用户是否比我老
        Db::startTrans();
        try{
            $shareMember = \app\common\model\Member::get($param['member']['boss']);
            $Member = \app\common\model\Member::get($param['userId']);
            //判断分享的用户是否还有上级
            if($shareMember->boss){
                $grade = 2;
            }else{
                $grade = 1;
            }
            if($Member){
                if($shareMember->createDate >= $Member->createDate){
                    return show(2,'新用户不能作为老用户上级','');
                }else{
                    if($Member->boss){
                        return true;
                    }else{
                        $Member->boss = $shareMember->id;
                        $Member->grade = $grade;
                        $Member->save();
                        //如果被绑定的人有下级（则所有的一级下级的grade变为2）
                        $membersons = \app\common\model\Member::where(['boss'=>$Member->id])->select();
                        $lists = [];
                        if($membersons){
                            foreach ($membersons as $v){
                                array_push($lists,['id'=>$v['id'],'grade'=>2]);
                            }
                            $MemberModel = new \app\common\model\Member();
                            $MemberModel->saveAll($lists);
                        }
                    }
                }
            }else{
                //此时说明我在member表中还不存在，没有上下级关系（说明分享的人比我老）
                $User = \app\common\model\User::get($param['userId']);
                $MemberModel = new \app\common\model\Member();
                $MemberModel->id = $param['userId'];
                $MemberModel->name = $User->userName;
                $MemberModel->grade = $grade;
                $MemberModel->boss = $shareMember->id;
                $MemberModel->status = 0;
                $MemberModel->createOper = $param['userId'];
                $MemberModel->type = 1;
                $MemberModel->save();
            }
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'绑定上下级关系成功','绑定上下级关系成功');
        }catch (Exception $ex){
            Db::rollback();
        }
    }




    private function getmemAllDis($memberId){
        $memAllDis = 0;
        $Distribution = Distribution::where(['memberId'=>$memberId])->where('bossId','<>','')->where('money','>',0)->select();
        if($Distribution){
            foreach ($Distribution as $item){
                $memAllDis += (int)$item['money'];
            }
        }

        return $memAllDis;
    }

    //获取我的店铺信息
    public function myStore(Request $request){
        $param = $request->param();
        $Userstore = Userstore::where('userId',$param['userId'])->find();
        $data = [];
        if(!$Userstore){
            return show(2,'您还没有店铺',null);
        }
        $Store = \app\admin\model\Store::get($Userstore->storeId);
        $data['store'] = $Store;
        return show(config('status.SUCCESS_STATUS'),'ok',$data);
    }

    //赚红包时保存用户信息
    public function bandUserInfo(Request $request){
        (new bandUserInfoValidate())->goCheck();
        $param = $request->param();
        $User = \app\common\model\User::get($param['userId']);
        if($User){
            $Member = \app\admin\model\Member::get($param['userId']);
            if($Member){
                $Member->name = $param['name'];
                $Member->phone = $param['phoneNumber'];
                $Member->status = 0;
                $Member->save();
            }else{
                $MemberModel = new \app\admin\model\Member();
                $MemberModel->id = $User->id;
                $MemberModel->name = $param['name'];
                $MemberModel->phone = $param['phoneNumber'];
                $MemberModel->status = 0;
                $MemberModel->save();
            }
            $User->userName = $param['name'];
            $User->phone = $param['phoneNumber'];
            $User->save();
            return show(config('status.SUCCESS_STATUS'),'ok',1);
        }else{
            return show(2,'用户信息异常',null);
        }
    }

    public function myPocket(Request $request){
        $param = $request->param();
        $firstDisMoney = 0;
        $Distribution = Distribution::where('bossId',$param['userId'])->where('money','>',0)->select();
        if($Distribution){
            foreach ($Distribution as $value){
                $firstDisMoney += (int)$value['money'];
            }
        }
        $Member = \app\admin\model\Member::where('id',$param['userId'])->find();
        $MemberMoney = $Member['distributeComm']?$Member['distributeComm']:0;
        $Usersettlement = Usersettlement::where('userId',$param['userId'])->select();
        $tixianmoney = 0;
        if($Usersettlement){
            foreach ($Usersettlement as $v){
                $tixianmoney += (int)$v['amount'];
            }
        }
        $sumMoney = $MemberMoney+$tixianmoney;
        $secDisMoney = $sumMoney - $firstDisMoney;
        $firstDisSize = \app\common\model\Member::where('boss',$param['userId'])->count();
        $aaa = \app\common\model\Member::where('boss',$param['userId'])->select();
        $secDisSize = 0;
        if($aaa){
            foreach ($aaa as $v){
                $scount = \app\common\model\Member::where('boss',$v['id'])->count();
                $secDisSize += $scount;
            }
        }

        $data['firstDisMoney'] = $firstDisMoney;
        $data['secDisMoney'] = $secDisMoney;
        $data['firstDisSize'] = $firstDisSize;
        $data['secDisSize'] = $secDisSize;
        $data['sumSize'] = $firstDisSize+$secDisSize;
        $data['sumMoney'] = $sumMoney;
        return show(1,'ok',$data);





    }
}